package com.lionmibi.mynotification;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.IBinder;
import android.provider.Settings;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.NotificationManagerCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends AppCompatActivity {

    private Button mButton,getButton,deleteButton,start_and_stop_Notification_Button;

    private EditText mEditText_set_number,mEditText_set_time,mEditText_set_first_show_time;

    private int notificationId=1,closenotificationId=1;

    private Timer timer;

    private int number_int,number=1;

//    private NotificationManager manager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mEditText_set_number=(EditText) findViewById(R.id.set_show_number);
        mEditText_set_time=(EditText) findViewById(R.id.set_show_time);
        mEditText_set_first_show_time=(EditText) findViewById(R.id.set_first_show_time);

        mEditText_set_time.setInputType(InputType.TYPE_CLASS_NUMBER);
        mEditText_set_number.setInputType(InputType.TYPE_CLASS_NUMBER);
        mEditText_set_first_show_time.setInputType(InputType.TYPE_CLASS_NUMBER);


        start_and_stop_Notification_Button=(Button) findViewById(R.id.start_notification);

        start_and_stop_Notification_Button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(start_and_stop_Notification_Button.getText().equals("开始发送")) {
                    if (timer == null) {
                        start_and_stop_Notification_Button.setText("取消发送");
                        number = 1;
                        String number_string = mEditText_set_number.getText().toString();
                        String time_string = mEditText_set_time.getText().toString();
                        String first_time_string = mEditText_set_first_show_time.getText().toString();
                        int number_int_from_text = 5;
                        int time_int_from_text = 2;
                        int first_time_from_text = 0;
                        final double time_int;
                        if (number_string != null && !number_string.equals("")) {
                            Log.d("number", "" + number_string);
                            number_int_from_text = Integer.parseInt(number_string);
                        }
                        number_int = number_int_from_text;

                        if (time_string != null && !time_string.equals("")) {
                            Log.d("time", "" + time_string);
                            time_int_from_text = Integer.parseInt(time_string);
                        }

                        if(first_time_string!=null && !first_time_string.equals("")){
                            Log.d("first_time",""+first_time_string);
                            first_time_from_text = Integer.parseInt(first_time_string);
                        }

                        if (time_int_from_text > 0) {
                            time_int = time_int_from_text;
                        } else if(time_int_from_text==0){
                            Toast.makeText(MainActivity.this, "当前使用一次性发完", Toast.LENGTH_SHORT).show();
                            time_int = 0.1;
                        }else {
                            Toast.makeText(MainActivity.this, "请不要时间输入无效值,当前使用默认设置2秒", Toast.LENGTH_SHORT).show();
                            time_int = 2;

                        }

                        timer = new Timer();
                        Log.d("Closedlistener", "发送开始");
                        TimerTask timerTask = new TimerTask() {
                            @Override
                            public void run() {
                                number_int--;
                                if (number_int < 0) {
                                    timer.cancel();
                                    timer = null;

                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            start_and_stop_Notification_Button.setText("开始发送");
                                        }
                                    });
                                }else {
                                    sendNotification();
                                    number++;
                                    closenotificationId++;
                                }
                            }
                        };
                        timer.schedule(timerTask, first_time_from_text*1000 , (int)(time_int * 1000));
                    }
                }else {
                    if(timer!=null){
                        timer.cancel();
                        timer=null;
                        Toast.makeText(MainActivity.this,"停止Timer成功",Toast.LENGTH_SHORT).show();
                        start_and_stop_Notification_Button.setText("开始发送");
                    }else{
                        Toast.makeText(MainActivity.this,"当前不存在Timer",Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });

        mButton=(Button) findViewById(R.id.send_Notification);

        mButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                sendNotification();
                number++;
                closenotificationId++;

//                Intent resultIntent=
//                        new Intent(MainActivity.this,Main2Activity.class);
//
//                PendingIntent resultPendingIntent=PendingIntent.getActivity(
//                        MainActivity.this, 0,resultIntent
//                        ,PendingIntent.FLAG_CANCEL_CURRENT
//                );
//
//                NotificationManager manager=
//                        (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
//
//
//                if(Build.VERSION.SDK_INT>=26){
//                    int importance=NotificationManager.IMPORTANCE_HIGH;
//                    NotificationChannel notificationChannel=
//                            new NotificationChannel(closenotificationId+"","mytestNotification",importance);
//                    manager.createNotificationChannel(notificationChannel);
//                    Notification notification=new Notification.Builder(MainActivity.this,closenotificationId+"")
//                            .setSmallIcon(R.drawable.small_icon)
//                            .setContentTitle("My Notification")
//                            .setContentText("哈哈哈哈哈哈哈")
//                            .setAutoCancel(true)
//                            //.setFullScreenIntent(resultPendingIntent,false)
//                            .setLargeIcon(
//                                    BitmapFactory.decodeResource(getResources(),R.drawable.small_icon))
//                            .build();
//                    manager.notify(closenotificationId,notification);
//
//                }else{
//                    NotificationCompat.Builder builder=
//                            new NotificationCompat.Builder(MainActivity.this)
//                                    .setSmallIcon(R.drawable.small_icon)
//                                    .setContentTitle("My Notification")
//                                    .setContentText("哈哈哈哈哈哈哈")
//                                    .setAutoCancel(true)
//                                    //.setFullScreenIntent(resultPendingIntent,false)
//                                    .setLargeIcon(
//                                            BitmapFactory.decodeResource(getResources(),R.drawable.small_icon));
//
//                    builder.setContentIntent(resultPendingIntent);
//
//                    Notification notification = builder.build();
//
//                    manager.notify(notificationId,notification);
//                }
//                notificationId++;
            }
        });

        final Intent intent=new Intent(MainActivity.this,NotificationListener.class);
        intent.setAction("android.service.notification.NotificationListenerService");

        getButton=(Button) findViewById(R.id.get_Notification);
        getButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openNotificationListenSettings();
            }
        });

        deleteButton=(Button) findViewById(R.id.delete_AllNotification);
        deleteButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(isNotificationListenerEnabled(MainActivity.this)){
                    Intent intent1=new Intent();
                    intent1.setAction("AAAA");
                    sendBroadcast(intent1);
                }else{
                    Toast.makeText(MainActivity.this,"还未开启权限",Toast.LENGTH_SHORT).show();
                }
            }
        });



    }


    private void sendNotification(){
        Intent resultIntent=
                new Intent(MainActivity.this,Main2Activity.class);

        PendingIntent resultPendingIntent=PendingIntent.getActivity(
                MainActivity.this, 0,resultIntent
                ,PendingIntent.FLAG_CANCEL_CURRENT
        );
        NotificationManager manager=
                (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        if(Build.VERSION.SDK_INT>=26){
            int importance=NotificationManager.IMPORTANCE_HIGH;
            NotificationChannel channel=new NotificationChannel(closenotificationId+"","mytestNotification",importance);
            manager.createNotificationChannel(channel);

            Notification notification=new Notification.Builder(MainActivity.this,closenotificationId+"")
                    .setSmallIcon(R.drawable.small_icon)
                    .setContentTitle("My Notification")
                    .setContentText("这是第"+closenotificationId+"个消息")
                    .setAutoCancel(true)
                    .setContentIntent(resultPendingIntent)
                    .setLargeIcon(BitmapFactory.decodeResource(getResources(),R.drawable.small_icon))
                    .build();

            manager.notify(closenotificationId,notification);
            Log.d("Closedlistener","第"+number+"次发送");
        }else{
            NotificationCompat.Builder builder
                    =new NotificationCompat.Builder(MainActivity.this)
                    .setSmallIcon(R.drawable.small_icon)
                    .setContentTitle("My Notification")
                    .setContentText("这是第"+closenotificationId+"个消息")
                    .setAutoCancel(true)
                    .setContentIntent(resultPendingIntent)
                    .setLargeIcon(BitmapFactory.decodeResource(getResources(),R.drawable.small_icon));
            Notification notification=builder.build();
            manager.notify(closenotificationId,notification);
            Log.d("Closedlistener","第"+number+"次发送");
        }


    }

    public boolean isNotificationListenerEnabled(Context context){
        Set<String> packageNames =
                NotificationManagerCompat.getEnabledListenerPackages(this);
        if(packageNames.contains(context.getPackageName())){
            return true;
        }
        return false;
    }

    public void openNotificationListenSettings() {
        try {
            Intent intent;
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP_MR1) {
                intent = new Intent(Settings.ACTION_NOTIFICATION_LISTENER_SETTINGS);
            } else {
                intent = new Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS");
            }
            startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
